package com.ml.rabbitmq.b_work.fair;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author xr-8
 * @create 2021-04-14 22:56
 */
public class Work1 {

    public static void main(String[] args) {
        //1创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
//        connectionFactory.setVirtualHost("/ ");

        Connection connection = null;
        Channel channel = null;
        try {
            //2创建连接Connection
            connection = connectionFactory.newConnection("消费者-Work1");
            //3通过连接获取通道Channel
            channel = connection.createChannel();
            Channel finalChannel = channel;
            //4定义接受消息的回调
            channel.basicQos(1);
            channel.basicConsume("queue1", false, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    try {
                        System.out.println("Work1收到消息是：" + new String(delivery.getBody(), "UTF-8"));
                        Thread.sleep(500);
                        finalChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("Work1接受失败了...");
                }
            });

            System.out.println("Work1开始接受消息!");
            System.in.read();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7关闭通道
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            //8关闭连接
            if (Objects.nonNull(connection) && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
